package com.mychat.service.impl;


import com.mychat.entity.Constants;
import com.mychat.entity.config.AppConfig;
import com.mychat.entity.query.SimplePage;
import com.mychat.enums.AppUpdateFileTypeEnum;
import com.mychat.enums.AppUpdateStatusEnum;
import com.mychat.enums.PageSize;
import com.mychat.entity.vo.PaginationResultVO;
import com.mychat.entity.po.AppUpdate;
import com.mychat.entity.query.AppUpdateQuery;
import com.mychat.enums.ResponseCodeEnum;
import com.mychat.exception.BusinessException;
import com.mychat.mappers.AppUpdateMapper;
import com.mychat.service.AppUpdateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.mychat.enums.AppUpdateStatusEnum;

/**
 * @Description:app发布ServiceImpl
 * @auther:YYT
 * @date:2025/03/08
 */
@Service("appUpdateService")
public class AppUpdateServiceImpl implements AppUpdateService {

	@Resource
	private AppUpdateMapper<AppUpdate, AppUpdateQuery> appUpdateMapper;

	@Resource
	private AppConfig appConfig;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<AppUpdate> findListByParam(AppUpdateQuery query) {
		return this.appUpdateMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	@Override
	public Integer findCountByParam(AppUpdateQuery query) {
		return this.appUpdateMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	@Override
	public PaginationResultVO<AppUpdate> findListByPage(AppUpdateQuery query) {
		Integer count = this.findCountByParam(query);
		Integer pageSize = query.getPageSize() == null ? PageSize.SIZE15.getSize(): query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(), count, pageSize);
		query.setSimplePage(page);
		List<AppUpdate> list = this.findListByParam(query);
		PaginationResultVO<AppUpdate> result = new PaginationResultVO<AppUpdate>(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(AppUpdate bean) {
		return this.appUpdateMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<AppUpdate> listBean) {
		if(listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<AppUpdate> listBean) {
		if(listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据Id查询
	 */
	@Override
	public AppUpdate getAppUpdateById(Integer id) {
		return this.appUpdateMapper.selectById(id);
	}

	/**
	 * 根据Id更新
	 */
	@Override
	public Integer updateAppUpdateById(AppUpdate bean, Integer id) {
		return this.appUpdateMapper.updateById(bean, id);
	}

	/**
	 * 根据Id删除
	 */
	@Override
	public Integer deleteAppUpdateById(Integer id) throws BusinessException {
		AppUpdate dbInfo = this.getAppUpdateById(id);
			if(!AppUpdateStatusEnum.INIT.getStatus().equals(dbInfo.getStatus())) {
				throw new BusinessException(ResponseCodeEnum.CODE_600);
			}
		return this.appUpdateMapper.deleteById(id);
	}

	/**
	 * 根据Version查询
	 */
	@Override
	public AppUpdate getAppUpdateByVersion(String version) {
		return this.appUpdateMapper.selectByVersion(version);
	}

	/**
	 * 根据Version更新
	 */
	@Override
	public Integer updateAppUpdateByVersion(AppUpdate bean, String version) {
		return this.appUpdateMapper.updateByVersion(bean, version);
	}

	/**
	 * 根据Version删除
	 */
	@Override
	public Integer deleteAppUpdateByVersion(String version) {
		return this.appUpdateMapper.deleteByVersion(version);
	}
	
	@Override
	public void saveUpdate(AppUpdate appUpdate, MultipartFile file) throws BusinessException, IOException {
		AppUpdateFileTypeEnum fileTypeEnum = AppUpdateFileTypeEnum.getEnumByType(appUpdate.getFileType());
		if(fileTypeEnum == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		if(appUpdate.getId() != null) {
			AppUpdate dbInfo = this.getAppUpdateById(appUpdate.getId());
			if(!AppUpdateStatusEnum.INIT.getStatus().equals(dbInfo.getStatus())) {
				throw new BusinessException(ResponseCodeEnum.CODE_600);
			}
		}

		AppUpdateQuery query = new AppUpdateQuery();
		query.setOrderBy("id desc");
		query.setSimplePage(new SimplePage(0, 1));
		List<AppUpdate> list = appUpdateMapper.selectList(query);
		if(!list.isEmpty()) {
			AppUpdate lastest = list.get(0);
			Long dbVersion = Long.parseLong(lastest.getVersion().replace(".", ""));
			Long currentVersion = Long.parseLong(appUpdate.getVersion().replace(".", ""));
			if(appUpdate.getId() == null && currentVersion <= dbVersion) {
				throw new BusinessException("当前版必须大于历史版本");
			}
			if(appUpdate.getId() != null && currentVersion <= dbVersion && !appUpdate.getId().equals(lastest.getId())) {
				throw new BusinessException("当前版必须大于历史版本");
			}

			AppUpdate versionDb = appUpdateMapper.selectByVersion(appUpdate.getVersion());
			if(appUpdate.getId() != null && versionDb != null && !appUpdate.getId().equals(versionDb.getId())) {
				throw new BusinessException("当前版本已存在");
			}
		}

		if(appUpdate.getId() == null) {
			appUpdate.setCreateTime(new Date());
			appUpdate.setStatus(AppUpdateStatusEnum.INIT.getStatus());
			appUpdateMapper.insert(appUpdate);
		} else {
			appUpdateMapper.updateById(appUpdate, appUpdate.getId());
		}
		if(file!=null) {
			File folder = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			file.transferTo(new File(folder.getAbsolutePath() , appUpdate.getId() + Constants.APP_EXE_SUFFIX));
		}
	}

	@Override
	public void postUpdate(Integer id, Integer status, String grayscaleUid) throws BusinessException {
		AppUpdateStatusEnum statusEnum = AppUpdateStatusEnum.getEnumByStatus(status);
		if(statusEnum == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		if(AppUpdateStatusEnum.GRAYSCALE == statusEnum && StringUtils.isEmpty(grayscaleUid)) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		if(AppUpdateStatusEnum.GRAYSCALE != statusEnum) {
			grayscaleUid = "";
		}
		AppUpdate update = new AppUpdate();
		update.setStatus(statusEnum.getStatus());
		update.setGrayscaleUid(grayscaleUid);
		appUpdateMapper.updateById(update, id);
	}

	@Override
	public AppUpdate getLatestUpdate(String appVersion, String uid) {
		return this.appUpdateMapper.selectLatestUpdate(appVersion, uid);
	}

}